package com.xiaoxiao.springbootstudy.controller;

import com.xiaoxiao.springbootstudy.pojo.Menu;
import com.xiaoxiao.springbootstudy.pojo.vo.MenuVO;
import com.xiaoxiao.springbootstudy.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class MenuController {

    @Autowired
    private MenuService menuService;

    @CrossOrigin
    @RequestMapping(path = "/allMenus", method = RequestMethod.GET)
    List<MenuVO> getMenus()
    {
        return menuService.getMenus();
    }

    @CrossOrigin
    @RequestMapping("/compIndex")
    public Integer compIndex(Integer id) {
        Menu menu = menuService.getById(id);
        return menu.getComponent();
    }

    @CrossOrigin
    @PostMapping("/saveMenu")
    public Map<String, Object> saveMenus(@RequestBody Menu menu) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", 400);
        map.put("msg", "添加失败");

        try {
            menuService.saveMenusService(menu);
            map.put("code", 200);
            map.put("msg", "添加成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    @CrossOrigin
    @GetMapping("/deleteMenus/{id}")
    public Map<String, Object> deleteMenus(@PathVariable Integer id) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 400);
        map.put("msg", "删除失败");

        try {
            menuService.removeById(id);
            map.put("code", 200);
            map.put("msg", "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    @CrossOrigin
    @PostMapping("/updateMenu")
    public Map<String, Object> updateMenu(@RequestBody Menu menu) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 400);
        map.put("msg", "更新成功");

        try {
            menuService.updateById(menu);
            map.put("code", 200);
            map.put("msg", "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
